package com.woniu.airent.controller;

import com.github.pagehelper.PageInfo;
import com.woniu.airent.dto.*;
import com.woniu.airent.service.HouseService;
import com.woniu.airent.utils.SnowFlakeShortUrl;
import com.woniu.airent.utils.TXYunUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

@Controller
@RequestMapping("houseUser")
public class HouseController {
    @Autowired
    HouseService houseService;

    @RequestMapping("/issueHouse")
    @ResponseBody
    public String issueHoue(HouseDto house,
                            @DateTimeFormat(pattern = "yyyy-MM-dd") Date date,
                            @RequestParam(value = "extrasCollections[]", required = false) String[] extrasCollection,
                            @RequestParam(value = "itemsCollections[]", required = false) String[] itemsCollection,
                            @RequestParam(value = "imgsPathes[]", required = false) String[] imgPath,
                            HttpServletRequest request) {

        UserDto user = (UserDto) request.getSession().getAttribute("user");
        house.setUserId(user.getUserId());
        house.setHouseNumber(Long.toString(new SnowFlakeShortUrl(2, 3).nextId()));
        house.setUpdateDate(new Date());
        house.setRentDate(new Date());
        house.setHouseState(0);
        house.setExamine(0);

        if (itemsCollection != null) {
            List<ItemsDto> items = new ArrayList<>();
            for (int i = 0; i < itemsCollection.length; i++) {
                ItemsDto itemsDto = new ItemsDto();
                itemsDto.setItemId(Integer.parseInt(itemsCollection[i]));
                items.add(itemsDto);
            }
            house.setItems(items);
        }

        if (extrasCollection != null) {
            List<ExtraDto> extras = new ArrayList<>();
            for (int i = 0; i < extrasCollection.length; i++) {
                ExtraDto extraDto = new ExtraDto();
                extraDto.setExtraId(Integer.parseInt(extrasCollection[i]));
                extras.add(extraDto);
            }
            house.setExtras(extras);
        }

        if (imgPath != null) {
            List<ImgsDto> imgs = new ArrayList<>();
            for (int i = 0; i < imgPath.length; i++) {
                ImgsDto imgsDto = new ImgsDto();
                imgsDto.setImgAdress(imgPath[i]);
                imgs.add(imgsDto);
            }
            house.setImgs(imgs);
            house.setFirstImg(imgPath[0]);
        }

        System.out.println(house);


        String result = houseService.addHouse(house);
        return result;
    }



    //腾讯云上传
    @Value("${tencent.path}")
    private String IMAGE_PATH;

    /**
     * 上传图片
     */
    @RequestMapping("/upload")
    @ResponseBody
    public Map<String, String> upload(@RequestParam("imgs") MultipartFile multipartFile) throws Exception {
        //获取文件的名称
        String fileName = multipartFile.getOriginalFilename();

        //获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));

        //使用uuid作为文件名，防止生成的临时文件重复
        final File excelFile = File.createTempFile("imagesFile-" + System.currentTimeMillis(), prefix);
        //将Multifile转换成File
        multipartFile.transferTo(excelFile);

        //调用腾讯云工具上传文件
        String imageName = TXYunUtil.uploadfile(excelFile, "avatar");

        //程序结束时，删除临时文件
        deleteFile(excelFile);

        //存入图片名称，用于网页显示
//        model.addAttribute("imageName", imageName);

        Map<String, String> map = new HashMap<>();
        map.put("success", imageName);

        //返回成功信息
        return map;
    }

    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }

    @RequestMapping("/showAllHouseNumber")
    public String showAllHouseNumber(@RequestParam(value = "userId") Integer userId, Model model){
        List<HouseDto> houses = houseService.findAllHouseByUserId(userId);
        model.addAttribute("house",houses);
        return "view/issuepost";
    }

    @ResponseBody
    @RequestMapping("showHouseSorted")
    public PageInfo<HouseDto> showHouseSorted(Integer pageNum, Integer sortMethod){
        PageInfo<HouseDto> houses = houseService.showHouse(pageNum, sortMethod);
        return houses;
    }

    @RequestMapping("detail")
    public String showDetail(Integer houseId, Map map){
        HouseDto houseDto = houseService.findHouseById(houseId);
        map.put("house",houseDto);
        return "view/housedesc";
    }

    @RequestMapping("showOneHouse")
    public String showOneHouse(@RequestParam(value = "houseId") int id,Map map){
        HouseDto houseDto=houseService.findHouseById(id);
        map.put("house",houseDto);
        return "housedesc";
    }
}
